<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="backlogPageData"
            :table-columns="backlogColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows"
            v-on:contradictionManage="contradictionManage"
            v-on:checkFlowHandle="checkFlowHandle">
          </app-table>
          <el-dialog :title="dialogTitle" :visible.sync="isCheckFlowDialogShow" :before-close="cancel" class="custom-dialog-style-imgDialog">
            <div id="imgContainer">
              <img :src="isImgData" style="width: 100%;" />
            </div>
          </el-dialog>
          <el-dialog :title="dialogTitle" :visible.sync="isManageEventDialogShow" :before-close="cancel" class="" :close-on-click-modal="false">
            <!-- <div class="block custom-timerShaftDialog-style"></div> -->
            <div style="height: 140px;border: 1px solid #ccc;border-radius: 4px; margin-bottom: 14px;margin-left: 28px;padding: 0 20px 3px 20px;clear: fixed">
              <div class="custom-content-left">
                <p>{{formData.eventSource}}--{{formData.reporterName}}</p>
                <p>{{formData.reportDate | formatDate}}</p>
                <p>{{formData.description}}</p>
              </div>
              <template v-if="formData.photoArr&&formData.photoArr.length>0">
                <div class="custom-img-right">
                <div v-for='(item,index) in formData.photoArr' class="timeTop-right" :key="index">
                  <img  :src="baseUrl+'/image/'+item" alt="" />
                </div>
                </div>
              </template>
            </div>
            <div class="custom-timerStatusContainer-style">{{status}}</div>
            <el-timeline pending>
              <el-timeline-item
                v-for="(activity, index) in activities"
                :key="index"
                :timestamp="activity.startTime | formatDate"
                placement="top">
                <el-card class="cardWapper">
                    <div class="cardLeft">
                      <p>任务名称：{{activity.taskName}}</p>
                      <p>处理人：{{activity.assigneeName}}</p>
                      <p v-for="(com,index) in activity.comments" :key="index">处理记录：{{com}}</p>
                      <div v-if="index === activities.length - 1">
                        <p v-if="activity.endTime === 0">状态：<span style="color:red;font-size:16px;">办理中...</span></p>
                        <p v-else>状态：<span style="color:red;font-size:16px;">已完结</span></p>
                      </div>
                    </div>
                   <div class="cardRight">
                      <template v-if="activity.photoArr&&activity.photoArr.length>0">
                        <div v-for='(item,index) in activity.photoArr' class="timeTop-right imgWapper" :key="index">
                          <img  :src="baseUrl+'/image/'+item" alt="" />
                        </div>
                      </template>
                    </div>
                  </el-card>
              </el-timeline-item>
            </el-timeline>
            <el-form :model="manageFormData" ref="manageFormData" :rules="rules1" class="custom-elForm-padding28">
              <el-form-item label="办理记录：" prop="comment" class="custom-textarea-height">
                <el-input type="textarea" v-model="manageFormData.comment"></el-input>
              </el-form-item>
              <el-form-item label="图片：" class="custom-label-unset">
                <app-upload ref="appUpload" v-model="manageFormData.photoArr" ></app-upload>
              </el-form-item>
              <el-form-item label="下一环节：" prop="outcome" class="custom-label-unset">
                <el-select v-model="manageFormData.outcome" clearable placeholder="请选择" @change="outcomeChangeEvt">
                  <el-option v-for="(manage,index) in manageOptions" :key="index"
                    :label="manage.name"
                    :value="manage.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="label" label-width="49%" v-if="isRegionSelectShow" prop="gridId">
                <el-select v-model="manageFormData.gridId" clearable placeholder="请选择">
                  <el-option v-for="(region,index) in regionOptions" :key="index"
                    :label="region.name"
                    :value="region.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="label" label-width="49%" v-if="isDeptOptionShow" prop="deptId">
                <el-select v-model="manageFormData.deptId" clearable placeholder="请选择">
                  <el-option v-for="(dept,index) in deptOptions" :key="index"
                    :label="dept.name"
                    :value="dept.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="label" label-width="49%" v-if="isRejectReasonSelectShow" prop="rejectReasonCategory">
                <el-select v-model="manageFormData.rejectReasonCategory" clearable placeholder="请选择">
                  <el-option v-for="(reject,index) in rejectOptions" :key="index"
                    :label="reject.name"
                    :value="reject.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save(true)">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            class="custom-dialog_style_twoLine"
            :before-close="cancel"
            :close-on-click-modal="false">
            <el-form :model="formData" label-width="50%">
              <el-form-item label="上报人：" label-width="30%">
                <el-input v-model="formData.reporterName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="上报人电话：" label-width="30%">
                <el-input v-model="formData.reporterContact" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="上报时间：" label-width="30%">
                <el-date-picker
                  v-model="formData.reportDate"
                  value-format="timestamp"
                  placeholder="选择日期时间"
                  :picker-options="dataPickerBeforeTodayOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="事件分类：" label-width="30%" style="margin-bottom: 22px">
                <div class="block">
                  <el-select filterable v-model="formData.eventCategory" placeholder="请选择">
                    <el-option v-for="(item,index) in eventCategoryOption"
                      :key="index"
                      :value="item.id"
                      :label="item.valueName"></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="经度：" label-width="30%">
                <el-input v-model="formData.longitude" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="纬度：" label-width="30%">
                <el-input v-model="formData.latitude" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="发生地点：" label-width="30%">
                <el-input v-model="formData.happenAddress" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="街道/社区/网格：" label-width="30%">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    filterable
                    clearable
                    :props="gridIdProps"
                    :show-all-levels="false"
                    v-model="formData.gridIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="事件描述：" label-width="30%" class="custom-textarea-container" style="width:100%">
                <el-input type="textarea" v-model="formData.description"></el-input>
              </el-form-item>
              <el-form-item label="" label-width="30%" class="custom-textarea-container">
              </el-form-item>
              <el-form-item label="图片：" class="custom-img-container" style="width:100%">
                <app-upload ref="appUpload" v-model="formData.photoArr" ></app-upload>
              </el-form-item>
              <el-form-item label="" label-width="30%" class="custom-textarea-container">
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppUpload from '@/components/AppMultiUpload'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import config from '@/config/index'
import {getAllRegion} from '@/utils/region'
import {getToken} from '@/utils/LocalDataUtil'
import {getEventCategory} from '@/data/DictData'
import {getUserGridTree, getUserInfo} from '@/utils/SessionDataUtil'
import {getDeptLevel, getGridLevel} from '@/http/AppApi'
import {findVerificationEvent, finishTasks, getTaskPhotoUrl, getTaskTimer, gitRrasonList, findEventDetail} from '@/http/EventApi'
export default {
  data () {
    return {
      status: '',
      activities: [],
      isImgData: '',
      treeData: [],
      backlogPageData: {},
      dialogTitle: '',
      isAnonymous: false,
      isDeptOptionShow: false,
      isRejectReasonSelectShow: false,
      isRegionSelectShow: false,
      backlogColumns: [
        { prop: 'taskName', label: '任务名称' },
        { prop: 'desc', label: '事件描述' },
        { prop: 'procsName', label: '所属流程' },
        { prop: 'createTime', label: '任务到达时间', formatter: this.dateFormatter }
      ],
      selectForm: {},
      manageFormData: {},
      manageOptions: [],
      isCheckFlowDialogShow: false,
      isManageEventDialogShow: false,
      manageOptionsProps: {
        value: 'value',
        label: 'name'
      },
      label: '',
      rules1: {
        comment: [
          { required: true, message: '请填写批注', trigger: 'blur' }
        ],
        outcomeArr: [
          { required: true, message: '请选择下一环节', trigger: 'blur' }
        ]
      },
      gridIdProps: {
        value: 'id',
        label: 'name',
        checkStrictly: true
      },
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      eventCategoryOption: [],
      currentSelectedData: [],
      dialogFormVisible: false,
      formData: {}
    }
  },
  components: {
    AppTree,
    AppTable,
    BtnGroup,
    AppUpload
  },
  mounted () {
    this.getTreeData()
    this.getTableData()
  },
  methods: {
    dateFormatter (row, column) {
      let prop = column.property
      let resTime = row[prop]
      return this.$moment(resTime).format('YYYY-MM-DD')
    },
    // 事件处理
    contradictionManage (data) {
      if (data && data.data) {
        let currentManageedData = data.data[data.index]
        this.dialogTitle = '事件处理'
        this.manageOptions = currentManageedData.options
        let isWorkflow = currentManageedData.procsInsId
        if (currentManageedData.procsInsId) this.$set(this.manageFormData, 'procsInsId', currentManageedData.procsInsId)
        else this.$set(this.manageFormData, 'businessId', currentManageedData.businessId)
        this.$set(this.manageFormData, 'taskId', currentManageedData.taskId)
        this.$set(this.manageFormData, 'isWorkflow', isWorkflow)
        this.isManageEventDialogShow = true
        this.uri = config.serverUrl
        let timerData = data.data[data.index]
        let isWorkflowTimer = true
        if (!timerData.procsInsId) isWorkflowTimer = false
        timerData.isWorkflowTimer = isWorkflowTimer
        this.timeLineStatus = timerData.status
        var m = this
        findEventDetail(currentManageedData.businessId).then(resp => {
          if (resp.code && resp.code === '200') {
            m.formData = resp.data
            let regionData = {}
            regionData.id = m.formData.gridId
            regionData.items = m.treeData
            m.formData.gridIdArr = getAllRegion(regionData)
          }
        })
        getTaskTimer(timerData).then(resp => {
          if (resp.code && resp.code === '200') {
            this.isTimerShaftDialogShow = true
            if (resp.data.historicTaskVo && resp.data.historicTaskVo instanceof Array) {
              var data = resp.data.historicTaskVo
              m.activities = data
              for (let i = 0; i < data.length; i++) {
                if (data[i].endTime === 0) m.status = '处理中'
                else m.status = '已完结'
              }
            }
          }
        })
      } else {
        return ''
      }
    },
    checkTimerShaftHandle (data) {
      if (data && data.data) {
        this.uri = config.serverUrl
        let timerData = data.data[data.index]
        let isWorkflowTimer = true
        if (!timerData.procsInsId) isWorkflowTimer = false
        timerData.isWorkflowTimer = isWorkflowTimer
        this.timeLineStatus = timerData.status
        var m = this
        getTaskTimer(timerData).then(resp => {
          if (resp.code && resp.code === '200') {
            this.isTimerShaftDialogShow = true
            if (resp.data.historicTaskVo && resp.data.historicTaskVo instanceof Array) {
              var data = resp.data.historicTaskVo
              for (let i = 0; i < data.length; i++) {
                const element = data[i]
                m.$set(m.activities, 'photoArr', m.toArray(m.activities.photo))
                element.photoArr = m.toArray(element.photo)
              }
              m.activities = data
              for (let i = 0; i < data.length; i++) {
                if (data[i].endTime === 0) m.status = '处理中'
                else m.status = '已完结'
              }
            }
          }
        })
      } else {
        return ''
      }
    },
    // 查看跟踪图
    checkFlowHandle (data) {
      if (data && data.data) {
        let flowData = data.data[data.index]
        let path = ''
        if (flowData.procsInsId) path = getTaskPhotoUrl(true) + flowData.procsInsId
        else path = getTaskPhotoUrl(false) + flowData.businessId
        let token = getToken()
        this.isCheckFlowDialogShow = true
        this.dialogTitle = data.data[data.index].desc
        this.isImgData = path + '?token=' + token
      }
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    save (isManageEventSave) {
      this.$refs['manageFormData'].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          this.formData = {}
          this.isManageEventDialogShow = false
          this.manageFormData.photo = this.manageFormData.photoArr instanceof Array && this.manageFormData.length > 0 ? this.manageFormData.photoArr.join(',') : ''
          finishTasks(this.manageFormData).then(resp => {
            if (resp.code && resp.code === '200') {
              this.$message({
                type: 'success',
                message: '处理成功，请在已办列表中查看'
              })
              this.isRegionSelectShow = false
              this.isDeptOptionShow = false
              this.isRejectReasonSelectShow = false
              this.manageFormData = {}
              this.getTableData()
            }
          })
        }
      })
    },
    cancel () {
      this.isCheckFlowDialogShow = false
      this.isManageEventDialogShow = false
      this.dialogFormVisible = false
      this.manageFormData = {}
      this.isImgData = ''
      this.$refs.appUpload.clearFileList()
    },
    getTableData (param) {
      findVerificationEvent(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.backlogPageData = resp.data
          this.backlogPageData.isCheckFlowHandleCol = true
          this.backlogPageData.checkPhotoTitle = '查看任务跟踪图'
          this.backlogPageData.manageTitle = '处理'
          if (this.backlogPageData.items && this.backlogPageData.items instanceof Array) {
            this.backlogTableData = this.backlogPageData.items
          }
        }
      })
    },
    toArray (string) {
      let arr = []
      if (string) {
        let stringArr = string.split(',')
        for (let i = 0; i < stringArr.length; i++) {
          let obj = {}
          obj.name = 'IMG_' + i
          obj.url = stringArr[i]
          arr.push(obj)
        }
        return string.split(',')
      } else {
        return []
      }
    },
    btnClickCallback (callbackData) {
      if (callbackData.rows.length !== 0) {
        if (callbackData.btnType === 'get') {
          let m = this
          findEventDetail(callbackData.rows[0].businessId).then(resp => {
            if (resp.code && resp.code === '200') {
              m.eventCategoryOption = getEventCategory()
              m.formData = resp.data
              let regionData = {}
              m.formData.eventCategoryArr = m.formData.eventCategory !== '' && m.formData.eventCategory !== null ? m.formData.eventCategory.split(',') : []
              regionData.id = m.formData.gridId
              regionData.items = m.treeData
              m.formData.gridIdArr = getAllRegion(regionData)
              m.$set(m.formData, 'photoArr', m.toArray(m.formData.photo))
              m.showOnly = callbackData.sohwOnly
              m.dialogTitle = callbackData.dialogTitle
              m.dialogFormVisible = true
            }
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请选择一条数据'
        })
        return ''
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
      } else {
        this.currentSelectedData = []
      }
    },
    handleCurrentChange (val) {
      if (val) this.selectForm.offset = val - 1
      else this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    appTreeClick (data) {
      this.selectForm.gridId = data.id
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    // 协调处理
    outcomeChangeEvt (val) {
      if (val) {
        this.isRejectReasonSelectShow = val === 'reject'
        let userInfo = getUserInfo()
        if (val === 'gridId') {
          let ids = {}
          ids.userId = userInfo.id
          ids.procsInsId = this.manageFormData.procsInsId
          getGridLevel(ids).then(resp => {
            if (resp.code && resp.code === '200') {
              this.isRegionSelectShow = true
              this.isDeptOptionShow = false
              this.isRejectReasonSelectShow = false
              this.label = '选择区域：'
              this.regionOptions = resp.data
            }
          })
        } else if (val === 'deptId') {
          getDeptLevel(userInfo.id).then(resp => {
            if (resp.code && resp.code === '200') {
              this.isDeptOptionShow = true
              this.isRegionSelectShow = false
              this.isRejectReasonSelectShow = false
              this.label = '职能部门：'
              this.deptOptions = resp.data
            }
          })
        } else if (val[0] === 'reject') {
          this.isRejectReasonSelectShow = true
          this.isDeptOptionShow = false
          this.isRegionSelectShow = false
          this.label = '请选择驳回原因：'
          gitRrasonList().then(resp => {
            if (resp.code && resp.code === '200') {
              this.rejectOptions = resp.data
              return false
            } else {
              this.rejectOptions = []
              return ''
            }
          })
          return ''
        } else {
          this.isRejectReasonSelectShow = false
          this.isDeptOptionShow = false
          this.isRegionSelectShow = false
        }
      } else {
        this.isRejectReasonSelectShow = false
        this.isDeptOptionShow = false
        this.isRegionSelectShow = false
      }
    }
  },
  filters: {
    formatDate: function (value) {
      let date = new Date(value)
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? ('0' + MM) : MM
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      let h = date.getHours()
      h = h < 10 ? ('0' + h) : h
      let m = date.getMinutes()
      m = m < 10 ? ('0' + m) : m
      let s = date.getSeconds()
      s = s < 10 ? ('0' + s) : s
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
    }
  }
}
</script>
<style scoped>
.custom-dialog-style-imgDialog .el-dialog{
  width: 82%;
}
.anonymityCheckbox{
  position: absolute;
  top: 3px;
  left: 220px;
}
#customCascaderStyle .el-cascader-menu{
  height: unset;
}
.custom-mar-bottom{
  margin-bottom: 74px !important;
}
.custom-mar-bottom .el-form-item__error{
  top: 80px;
  width: 200px;
}
.custom-timerShaftDialog-style {
  height: auto!important;
}
.custom-dialog_style_twoLine >>> .el-dialog__body {
  padding: 30px 18px
}
.custom-dialog_style_twoLine .el-form >>> .custom-img-container .el-form-item__content {
  position: relative
}
.custom-dialog_style_twoLine .el-form >>> .custom-img-container .el-form-item__label {
  width: 25%!important
}
.custom-dialog_style_twoLine >>> .el-form .custom-img-container {
  margin-bottom: 0px
}
.custom-dialog_style_twoLine .el-form >>> .custom-textarea-container .el-textarea {
  position: relative;
  top: 0
}
.custom-dialog_style_twoLine .el-form >>> .custom-textarea-container .el-form-item__label {
  width: 25%!important
}
.custom-dialog_style_twoLine .el-form >>> .custom-textarea-container {
   margin-bottom: 20px
}
.custom-content-left,
.custom-img-right{
  height: 120px;
  margin-top:10px;
  overflow: hidden;
}
.custom-content-left{
  width: 73%;
  float: left;
  line-height: 200%;
  overflow: hidden;
}
.custom-content-left p:nth-child(3){
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.custom-img-right{
  width: 26%;
  float: right;
  border: 1px solid #c28d3c
}
.timeTop-right {
  text-align: center;
  /* Center slide text vertically */
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  height: 100%
}
.cardRight {
  height: auto;
  overflow: hidden;
}
.timeTop-right img {
  width: 100%;
}
.imgWapper {
  width: 189px;
  float: left;
  height: 121px;
  overflow: hidden;
  border: 1px solid #c28d3c;
  margin: 5px 5px;
  border-radius: 3px
}
</style>
<style>
.custom-label-unset .el-form-item__label{
  float: unset;
}
.custom-elForm-padding28{
  padding-left: 28px;
}
.custom-textarea-height textarea{
  height: 120px;
}
</style>
